#include "buzzer.h"
#include<stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_io.h"
#include "hi_i2c.h"
#include  "hi_types_base.h"
#define AP3216C_ADDR (0X1E<<1)
//人体接近功能开启
void ps_setconfigure(void)
{
    hi_i2c_data data;
    hi_u8 buf[2]={0x0,0x4};
    int ret;

    data.send_buf=buf;
    data.send_len=2;

    //系统寄存器0x00为0x04 软复位一下
    ret=hi_i2c_write(HI_I2C_IDX_0,AP3216C_ADDR,&data);
    if(ret!=0)
    {
        printf("write 0x%x data 0x%x,ret if %d\n",buf[0],buf[1],ret);
        return;
    }
    
    //等待500ms
    usleep(500000);
    //系统寄存器0x00为0x3 所有功能开启
    buf[1]=0x3;
    ret=hi_i2c_write(HI_I2C_IDX_0,AP3216C_ADDR,&data);
    if(ret!=0)
    {
        printf("write 0x%x data 0x%x,ret if %d\n",buf[0],buf[1],ret);
        return;
    }
    return;

}
//传感器初始化
void ps_init(void)
{
    int ret;
    //设置IO口，IO10是SDA
    //IO9是SCL
    ret=hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_I2C0_SDA);
    
    if(ret!=0)
    {
        printf("set gpio 10 failed\n");
       return;
    } 
    ret=hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_I2C0_SCL);
    
    if(ret!=0)
    {
        printf("set gpio 9 failed\n");
         return;
    }
    ret=hi_io_set_pull(HI_IO_NAME_GPIO_10, HI_IO_PULL_UP);
    if(ret!=0)
    {
        printf("set gpio 10 up failed\n");
       return;
    } 
    ret=hi_io_set_pull(HI_IO_NAME_GPIO_9, HI_IO_PULL_UP);
    if(ret!=0)
    {
        printf("set gpio 9 up failed\n");
       return;
    } 
    //初始化i2c
    hi_i2c_init(HI_I2C_IDX_0,I2C_RATE_DEFAULT);
    if(ret!=0)
    {
        printf("Init i2c failed\n");
       return;
    } 
   
    //配置为人体接近功能的开启
    ps_setconfigure();
    printf("ps init sucess\n");
}

//获取人体接近的值
int ps_getdata(void)
{
    int value;
    hi_i2c_data data;
    hi_u8 buf=0xe;//读0xe和0x
    hi_u8 rbuf[2]={0};//读两位数据，高位在buf[1]，低位在buf[0]]

    int ret;

    //写寄存器地址oxe
    data.send_buf=&buf;
    data.send_len=1;


    ret=hi_i2c_write(HI_I2C_IDX_0,AP3216C_ADDR,&data);
    if(ret!=0)
    {
        printf("write ox%d data failed.%d\n",buf,ret);
    }
    
    data.receive_buf=rbuf;
    data.receive_len=2;
    ret=hi_i2c_read(HI_I2C_IDX_0,AP3216C_ADDR,&data);
    if(ret!=0)
    {
        printf("read buf failed.%d",ret);
        return;
    }
    printf("Read 0x%x data 0x%x  0x%x.\n",buf,rbuf[0],rbuf[1]);
    if(rbuf[0]&0x40||(rbuf[1]&0x40))
    {
        value=0;
    }
    else
    {
        value=(rbuf[0]&0xF)|((rbuf[1]&0x3F)<<4);
    }
       
}